	// Read a page's GET URL variables and return them as an associative array.
	function getVars(url)
	{
	    var formData = new FormData();
	    var split;
	    $.each(url.split("&"), function(key, value) {
	        split = value.split("=");
	        formData.append(split[0], decodeURIComponent(split[1].replace(/\+/g, " ")));
	    });
	
	    return formData;
	}
	
	// Variable to store your files
	var files;
	
	$( document ).delegate('#input-edf','change', prepareUpload);
	
	// Grab the files and set them to our variable
	function prepareUpload(event)
	{
	    files = event.target.files;
	}
	/* 
	 * JTable sesiones
	 */
	$(document).ready(function() {              

	    $('#TablaSesiones').jtable({
	        title: ' ',
	        selecting: true, //Enable selecting 
	        paging: false, //Enable paging
	        pageSize: 10, //Set page size (default: 10)
	        sorting: true, //Enable sorting
            defaultSorting: 'Fechaalta DESC', //Set default sorting
	        actions: {
	        	listAction: 'sesiones/getSesiones',
	            updateAction: function (postData) {
                    var formData = getVars(postData);

                    if($('#input-edf').val() !== ""){
                        formData.append("userfile", $('#input-edf').get(0).files[0]);
                        formData.append("solicitudid",$('#solicitudid').val());
                    }

                    return $.Deferred(function ($dfd) {
                        $.ajax({ 
                            url: 'sesiones/updSesion',
                            type: 'POST',
                            dataType: 'json',
                            data: formData,
                            processData: false, // Don't process the files
                            contentType: false, // Set content type to false as jQuery will tell the server its a query string request
                            success: function (data) {
                                $dfd.resolve(data);
                                $('#table-container').jtable('load');
                            },
                            error: function () {
                                $dfd.reject();
                            }
                        });
                    });
                },
	        },
	        fields: {
	        	Sesionid: {
	                key: true,
	                visibility: 'hidden',
	            },
	        	Solicitudid: {
	                key: true,
	                visibility: 'hidden',
	            },
	            Duracion:{
	                title: 'Minutos',
	                width: '20%',
	                create: false,
	                edit: true,
	                sorting: false
	            },
	            	
	            Fechaalta: {
	                title: 'F.alta',
	                width: '10%',
	                create: false,
	                edit:false,
	                sorting: false
	            },
	            Estadoid: {
	                title: 'Estado',
	                width: '20%',
	                options: function(data){
	                	return 'sesiones/getEstados' 
	                },
	                //options: { '1': 'Inactiva', '2': 'Activa', '4': 'Anulada' },
	                defaultValue:'0',
	                create: true,
	                edit: true,
	                sorting: false
	            },
	            ModUsername: {
	                title: 'Creador',
	                width: '15%',
	                create: false,
	                edit: false,
	                sorting: false
	            },
	            Dispid: {
	                title: 'Dispositivo',
	                options: function(data){
	                	return 'sesiones/getDispositivos?centroid='+$("#centroid").val() + '&sesid='+ data.record.Sesionid 
	                },
                    list: false
	               
	            },
	            Dispname: {
	                title: 'Dispositivo',
	                list: true,
	                sorting: false,
	                edit: false,
	                width:'15%'
	        	},
	            Fichero: {
                    title: 'EDF',
                    type: 'file',
                    create: false,
                    edit: false,
                    sorting: false,
                    list: true,
                    display: function(data){
                    	if (data.record.Rutafichero==null){
                    		return '<img src="/plantilla/images/fichero.gif" width="64" height="26" class="preview">';
                    	}else{
                    		return '<a href="sesiones/descargarFichero?fichero='+  data.record.Sesionid + '" ><img src="/plantilla/images/fichero_cargado.gif" width="64" height="26" class="preview"></a>';
                    	}
                    },
                    width: "10%",
                    listClass: "class-row-center"
                },
	            Rutafichero: {
                    title: 'Fichero EDF',
                    edit:true,
                    list:false,
                    create: false,
                    input: function(data) {
                        html = '<input id="conedf" name="conedf" value="'+ data.record.Rutafichero +'" type="hidden"><input type ="file" id="input-edf" name="edf" accept=".ecg,.edf"/>';
                        return html;
                    }
                },	            
	            Mediconame: {
	            	title: 'Medico',
	            	list: false,
	                create: false,
	                edit: true,
                	input: function (data) {
	                        return '<input type="text" readonly class="jtable-input-readonly" name="Mediconame" value="' + data.value + '"/>';
	                }
	            },
	            Medicoid: {
	            	title: 'Medicoid',
		            create: false,
		            edit: false,
		            list: false,
		            type: 'hidden'	            
	            },
	            Observaciones: {
	            	title: 'Observaciones',
	            	type: 'textarea', 
	            	list: false,
	                edit: true,
	                create: true,
	                inputClass: 'textarea_disp'
	            },
	            Fmod: {
	            	title: 'F. Modificación',
	            	list: false,
	                create: false,
	                edit: true,
	                input: function (data) {
	                        return '<input type="text" readonly class="jtable-input-readonly" name="Fmod" value="' + data.value + '"/>';
	                }
	            },
	            Centroid: {
	            	edit: true,
	            	type: 'hidden'
	            }
	            
	        },
	        
	      //Initialize validation logic when a form is created
            formCreated: function (event, data) {
                data.form.validationEngine();
            },
            //Validate form when it is being submitted
            formSubmitting: function (event, data) {
            	data.form.validationEngine('hideAll');
            	//Si el estado es activa y no se ha seleccionado un fichero
            	if ($("#Edit-Estadoid").val()=="2" && $("#input-edf").val()=="" && $("#conedf").val()=="null"){
            		data.form.find('input[name="edf"]').addClass('validate[required]');
            		data.form.find('input[name="Duracion"]').addClass('validate[required]');
            	}else{
            		data.form.find('input[name="edf"]').removeClass('validate[required]');
            	}
            	
            	if ($("#Edit-Estadoid").val()=="4" && $("#Edit-Observaciones").val()==""){
            		data.form.find('textarea[name="Observaciones"]').addClass('validate[required]');
            	}else{
            		data.form.find('textarea[name="Observaciones"]').removeClass('validate[required]');
            	}
            	
                return data.form.validationEngine('validate');
            },
            //Dispose validation logic when form is closed
            formClosed: function (event, data) {
                data.form.validationEngine('hide');
                data.form.validationEngine('detach');
            },
	        //Register to selectionChanged event to hanlde events                                     
	        recordAdded: function(event, data){
	            //after record insertion, reload the records
	            $('#TablaSesiones').jtable('load');
	        },
	        recordUpdated: function(event, data){
	            //after record updation, reload the records
	        	 $('#TablaSesiones').jtable('load', {
	     	    	solicitudid: $('#solicitudid').val()
	             });
	        },
	        recordsLoaded: function(event, data) {
	        	
	        	   var $selectedRows = $('#TablaSesiones tr:last');
	        	   
	               $selectedRows.each(function () {
	            	   //Si el estado es inactiva , se permite modificar.
	            	   if ($(this).data('record').Estadoid==1 ){
	            		   $(this).find('.jtable-edit-command-button').show();
	            	   }
	                   //var record = $(this).data('record');
	               });
	        	
	        },
	        rowInserted: function (event, data) {
	        	data.row.find('.jtable-edit-command-button').hide();
	        }
	    });
	    $('#TablaSesiones').jtable('load', {
	    	solicitudid: $('#solicitudid').val()
        });
	    
	    function refreshTable(fichero) {
	    	   $.post("sesiones/descargarFichero", "fichero="+fichero,
	    	       function(results)
	    	       {
	    	           $('#MyTableDiv').jtable('reload');
	    	       }
	    	       , "json");
	    	 }
	                
	});


	